#include "./listdefine.h" // 引入自己编写的 h 文件

// 创建双循环链表
DoublyLinkList createList();

// 删除元素
void delete(DoublyLinkList D);
// 插入元素(末尾)
void insert(DoublyLinkList D, char data);

int main()
{
    DoublyLinkList linkList = createList();
    printDoublyList(linkList);
    insert(linkList, 'm');
    printDoublyList(linkList);
    return 0;
}

DoublyLinkList createList()
{
    DLNode *start = (DoublyLinkList)malloc(sizeof(DLNode));
    start->data = getchar();
    // 结束结点 == 开始结点
    DLNode *end = start;

    DLNode *node;
    char ch;
    while ((ch = getchar()) != '\n')
    {
        node = (DoublyLinkList)malloc(sizeof(DLNode));
        node->data = ch;
        // end 相关的操作实际就是 start 的操作
        end->next = node;
        node->prev = end;
        // 最后一个结点等于新结点
        end = node;
    }

    end->next = start;
    start->prev = end;
    return start;
}

void insert(DoublyLinkList D, char data)
{
    DLNode *newNode = (DoublyLinkList)malloc(sizeof(DLNode));
    newNode->data = data;
    newNode->next = NULL;

    if (D == NULL)
    {
        newNode->prev = NULL;
        D = newNode;
    }
    else
    {   
        DLNode *lastNode = D;
        // 遍历至链表末尾
        while (lastNode->next != D)
        {
            lastNode = lastNode->next;
        }
        
        // 插入新结点
        lastNode->next = newNode;
        newNode->prev = lastNode;
    }
    // 创建循环
    newNode->next = D;
    D->prev = newNode;
}
